import React,{useState, useEffect} from 'react';
import { Input } from 'antd';
import CustomIcon from '@/components/CustomIcon';
import s from './style.less';
import SearchReturnBox from './SearchReturnBox';
import { useHistory } from 'react-router-dom';


const SearchInput = ()=>{
  const [searchReturn, setSearchReturn] = useState(null);
  const [searchInput, setSearchInput] = useState(null);
  const RES_LIMIT = 10;
  const TYPE = 1; // 搜索类型
  const history = useHistory();
  

    // 对输入进行防抖处理
    const debounce = (fun, delay)=>{
        let timer;
        return function (){
            let ctx = this;
            let args = arguments;
            clearTimeout(timer);
            timer = setTimeout(()=>{
                fun.apply(ctx, args);
            },delay)
        }
    }

  // searchInput的Effect
  useEffect(async ()=>{
    if(searchInput && searchReturn){
        const {data} = await React.$axios.get(`/search/suggest?limit=${RES_LIMIT}&keywords=${searchInput}&type=${TYPE}`);
        if(data.result.songs){
            // console.log(data.result.songs)
            setSearchReturn([...data.result.songs]);
        }
    }
    if(searchInput === ''){
        const {data} = await React.$axios.get(`/search/hot`);
        if(data.result.hots){
            setSearchReturn([...data.result.hots]);
        }
    }
  },[searchInput])
  
  // 向输入框中输入内容
  const handleInputChange = (e) =>{
      setSearchInput(e.target.value);
  }

  // 输入框失去焦点
  const handleInputBlur = () => {
    setTimeout(()=>setSearchReturn(null),100);
  }

  // 点击输入框
  const handleInputClick = async () => {
      if(!searchInput){
        const {data} = await React.$axios.get(`/search/hot`);
        if(data){
            setSearchReturn([...data.result.hots]);
        }
      }else{
        const {data} = await React.$axios.get(`/search/suggest?limit=${RES_LIMIT}&keywords=${searchInput}&type=${TYPE}`);
        if(data){
            setSearchReturn([...data.result.songs]);
        }
      }
  }

  // 点击推荐的歌曲
  const handleItemClick = (e)=>{
    history.push(`/searchresult/songs/${e.target.innerHTML}`);
    setSearchReturn(null);
    setSearchInput(e.target.innerHTML);
  }

    return (
        <div className={s.searchBox}>
        <Input
          size="large"
          placeholder="搜索喜欢的歌曲/歌手/歌单..."
          prefix={<CustomIcon type="icon-search" />}
          onPressEnter={()=>{
              if(searchInput === ''){
                  history.push('/');
              }else{
                history.push(`/searchresult/songs/${searchInput}`)
              }
            }}
        //   onChange={debounce(handleInputChange,300)}
          onChange={handleInputChange}
          onBlur={handleInputBlur}
          onClick={handleInputClick}
          value={searchInput}
        />
        {searchReturn && 
        <SearchReturnBox 
        data={searchReturn} 
        handleItemClick={handleItemClick}
        />}
      </div>
    )
}

export default SearchInput;